import Taro from '@tarojs/taro'
import { authService } from '../services/auth'
import type { User, LoginResponse } from '../types/api'

interface WechatLoginResult {
  code: string
  errMsg: string
}

interface WechatUserInfo {
  encryptedData: string
  iv: string
  userInfo: {
    nickName: string
    avatarUrl: string
    gender: number
    city: string
    province: string
    country: string
  }
}

class WechatAuthManager {
  async checkLoginStatus(): Promise<boolean> {
    try {
      const session = await Taro.checkSession()
      return authService.isLoggedIn()
    } catch (error) {
      authService.clearUserData()
      return false
    }
  }

  async login(): Promise<LoginResponse> {
    try {
      const loginResult = await this.getWechatCode()
      const userInfo = await this.getUserProfile()

      const loginParams = {
        code: loginResult.code,
        encryptedData: userInfo?.encryptedData,
        iv: userInfo?.iv
      }

      const response = await authService.login(loginParams)
      return response
    } catch (error: any) {
      throw new Error(`微信登录失败: ${error.message}`)
    }
  }

  private async getWechatCode(): Promise<WechatLoginResult> {
    return new Promise((resolve, reject) => {
      Taro.login({
        success: (result) => resolve(result),
        fail: (error) => reject(error)
      })
    })
  }

  private async getUserProfile(): Promise<WechatUserInfo | null> {
    return new Promise((resolve) => {
      Taro.getUserProfile({
        desc: '用于完善用户资料',
        success: (result) => resolve(result),
        fail: () => resolve(null)
      })
    })
  }

  async requireLogin(): Promise<User> {
    const isLoggedIn = await this.checkLoginStatus()

    if (!isLoggedIn) {
      await this.showLoginModal()
      const loginResult = await this.login()
      return loginResult.user
    }

    return authService.getUserInfoFromStorage()!
  }

  private async showLoginModal(): Promise<void> {
    return new Promise((resolve, reject) => {
      Taro.showModal({
        title: '登录提示',
        content: '需要登录后才能使用此功能',
        confirmText: '立即登录',
        cancelText: '取消',
        success: (result) => {
          if (result.confirm) {
            resolve()
          } else {
            reject(new Error('用户取消登录'))
          }
        }
      })
    })
  }

  async logout(): Promise<void> {
    try {
      await authService.logout()

      Taro.showToast({
        title: '退出成功',
        icon: 'success'
      })

      setTimeout(() => {
        Taro.reLaunch({
          url: '/pages/index/index'
        })
      }, 1500)
    } catch (error) {
      Taro.showToast({
        title: '退出失败',
        icon: 'none'
      })
    }
  }
}

export const wechatAuth = new WechatAuthManager()
export default wechatAuth